<template>
  <div class="property-form">
    <el-collapse v-model="activeNames" @change="handleChange">
      <!-- 模型设置 -->
      <el-collapse-item title="模型设置" name="basic" class="card-collapse-item">
        <el-form label-position="top" label-width="100px">
          <el-select v-model="node.data.model" placeholder="请选择模型" :loading="loading" @change="handleModelChange">
            <el-option v-for="option in modelOptions" :key="option.value" :label="option.label" :value="option.value" />
          </el-select>
        </el-form>
      </el-collapse-item>

      <el-collapse-item title="选择MCP服务" name="mcp" class="card-collapse-item">
        <el-form label-position="top" label-width="100px">
          <el-select v-model="node.data.mcpId" placeholder="请选择MCP服务" style="width: 100%" @change="handleMcpChange">
            <el-option v-for="mcp in mcps" :key="mcp.value" :label="mcp.label" :value="mcp.value" />
          </el-select>
        </el-form>
      </el-collapse-item>

      <!-- 适用场景 -->
      <el-collapse-item name="scene" class="card-collapse-item">
        <template #title>
          <span class="collapse-title required">适用场景</span>
          <el-tooltip content="请描述该模型适用的业务场景" placement="top" :show-after="500">
            <el-icon>
              <Warning />
            </el-icon>
          </el-tooltip>
        </template>
        <el-form label-position="top" label-width="100px">
          <el-input type="textarea" v-model="node.data.scene" placeholder="请描述该模型适用的业务场景" :rows="3"
            @blur="handleSceneBlur" />
        </el-form>
      </el-collapse-item>

      <!-- 输入输出 -->
      <el-collapse-item title="输入输出配置" name="io" class="card-collapse-item">
        <el-form label-position="top" label-width="100px">
          <el-form-item label="输入字段">
            <el-input v-model="node.data.inputField" placeholder="例如: input_text" />
          </el-form-item>
          <el-form-item label="输出字段">
            <el-input v-model="node.data.outputField" placeholder="例如: output_text" />
          </el-form-item>
        </el-form>
      </el-collapse-item>

      <!-- 高级设置 -->
      <el-collapse-item title="高级设置" name="advanced" class="card-collapse-item">
        <el-form label-position="top" label-width="100px">
          <el-form-item label="最大上下文长度">
            <el-input-number v-model="node.data.maxContextLength" :min="128" :max="8192" />
          </el-form-item>
          <el-form-item label="温度（Temperature）">
            <el-slider v-model="node.data.temperature" :min="0" :max="1" :step="0.01" />
          </el-form-item>
        </el-form>
      </el-collapse-item>
    </el-collapse>
  </div>
</template>

<script setup lang="ts" name="ChatModelProperty">
import { defineProps, ref, inject, onMounted } from "vue";
import type { Node } from "@vue-flow/core";
import { useVueFlow } from "@vue-flow/core";
import { Warning } from "@element-plus/icons-vue";
import type { FlowAPI, ModelType } from "@/types/types";
import { ElMessage } from "element-plus";

const props = defineProps<{
  node: Node;
}>();

const flowAPI = inject<FlowAPI>("flowAPI");

const modelOptions = ref<{ label: string; value: number }[]>([]);
const mcps = ref<{ label: string; value: number }[]>([]);
const loading = ref(false);

const { updateNode } = useVueFlow();

const loadModels = async () => {
  if (!flowAPI?.getModelList) {
    ElMessage.error("获取模型列表失败");
    return;
  }

  loading.value = true;

  try {
    const res = await flowAPI.getModelList();

    if (res.code === 200 && Array.isArray(res.data)) {
      modelOptions.value = res.data.map((model) => ({
        label: model.Name,
        value: model.ID,
      }));
    } else {
      ElMessage.warning("模型列表为空");
      modelOptions.value = [];
    }
  } catch (err) {
    ElMessage.error("加载模型列表失败");
  } finally {
    loading.value = false;
  }
};

const handleMcpChange = (index: number) => {
  const selectedMcp = mcps.value.find((mcp) => mcp.value === index);
  if (selectedMcp) {
    updateNode(props.node.id, {
      data: {
        ...props.node.data,
        mcpId: selectedMcp.value,
        mcpName: selectedMcp.label,
      },
    });
  }
};

const handleModelChange = (selectedId: number) => {
  const selectedModel = modelOptions.value.find((opt) => opt.value === selectedId);
  if (selectedModel) {
    updateNode(props.node.id, {
      data: {
        ...props.node.data,
        model: selectedModel.value,
        modelName: selectedModel.label,
      },
    });
  }
};

const activeNames = ref(["basic", "scene", "io", "advanced", "mcp"]);

const handleChange = (names: string[] | string) => {
  console.log("展开/收起的面板:", names);
};

const originalScene = ref(props.node.data.scene);
const handleSceneBlur = () => {
  console.log("场景输入框失去焦点");
  if (!originalScene.value) {
    updateNode(props.node.id, {
      data: {
        ...props.node.data,
        data: {
          scene: originalScene.value,
        },
      },
    });
  }
};

const loadMcps = async () => {
  if (!flowAPI?.getMcpList) return;

  loading.value = true;
  try {
    const res = await flowAPI.getMcpList();
    if (res.code === 200 && Array.isArray(res.data)) {
      mcps.value = res.data
        .filter((mcp) => mcp.Tools && mcp.Tools.length > 0)
        .map((mcp) => ({
          label: `${mcp.Name} (${mcp.McpType})`,
          value: mcp.ID,
        }));
      mcps.value.unshift({
        label: "未设置",
        value: 0,
      });
    }
  } catch (err) {
    console.error("获取 MCP 列表失败:", err);
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  loadModels();
  loadMcps();
});
</script>

<style scoped>
.property-form {
  width: 100%;
  padding: 10px;
}

.collapse-title {
  flex: 1;
  font-size: 14px;
}

.collapse-title.required::after {
  content: "* ";
  color: red;
  margin-right: 4px;
}

.card-collapse-item {
  background-color: #f7f9fc;
  /* 卡片背景色 */
  border-radius: 6px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  margin-bottom: 16px;
  overflow: hidden;
  transition: all 0.3s ease;
}

.card-collapse-item:hover {
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
}

.card-collapse-item ::v-deep(.el-collapse-item__header) {
  background-color: #eef2f6;
  font-weight: bold;
  padding-left: 12px;
  line-height: 32px;
  /* 默认可能是 40~48px，可调低 */
  min-height: 32px;
  /* 控制最小高度 */
  height: 32px;
  /* 固定高度 */
  border-bottom: none;
  transition: background-color 0.3s ease;
}

.card-collapse-item ::v-deep(.el-collapse-item__wrap) {
  border-top: none;
  padding: 16px;
  background-color: #ffffff;
}

/* 👇 关键：取消内容区域底部的 padding */
.card-collapse-item ::v-deep(.el-collapse-item__content) {
  padding-bottom: 0;
}

.el-form {
  margin-bottom: 10px;
  background-color: transparent;
}
</style>
